package org.oos.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import org.oos.service.impl.OOSServiceImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
public class OOSController {

    @Resource
    private OOSServiceImpl oosService;

    /**
     * @return FileUploadResult
     * @desc 文件上传到oss
     * @Param uploadFile
     */
    @RequestMapping("file/upload")
    @ResponseBody
    public void upload(@RequestParam("file") MultipartFile uploadFile) throws Exception {
        oosService.upload(uploadFile);
    }

    /**
     * @return FileUploadResult
     * @desc 根据文件名删除oss上的文件
     * @Param objectName
     */
    @RequestMapping("file/delete")
    @ResponseBody
    public void delete(@RequestParam("fileName") String objectName) throws Exception {
        oosService.delete(objectName);
    }

    /**
     * @return List<OSSObjectSummary>
     * @desc 查询oss上的所有文件
     * @Param
     */
    @RequestMapping("file/list")
    @ResponseBody
    public List<OSSObjectSummary> list() throws Exception {
        return this.oosService.list();
    }

    /**
     * @return
     * @desc 根据文件名下载oss上的文件
     * @Param objectName
     */
    @RequestMapping("file/download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(objectName.getBytes(),
                        StandardCharsets.ISO_8859_1));

        oosService.download(response.getOutputStream(), objectName);
    }

}
